<template>
  <!-- 发放记录明细表单弹窗 -->

  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="90">
      <el-row>
        <el-col :span="12">
          <el-form-item label="企业编号" prop="assetCode">
            <el-input
              disabled
              v-if="!props.isReadonly"
              v-model="formData.assetCode"
              placeholder="请输入企业编号"
              clearable
            />
            <span v-else>{{ formData.assetCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="器具名称" prop="assetName">
            <el-input
              disabled
              v-if="!props.isReadonly"
              v-model="formData.assetName"
              placeholder="请输入器具名称"
              clearable
            />

            <span v-else>{{ formData.assetName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="放发日期" prop="grantDate">
            <el-input
              disabled
              v-if="!props.isReadonly"
              v-model="formData.grantDate"
              placeholder="请输入放发日期"
              clearable
            />
            <span v-else>{{
              formData.grantDate
                ? dayjs(formData.grantDate).format("YYYY-MM-DD")
                : ""
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="放发原因" prop="grantReason">
            <el-input
              disabled
              v-if="!props.isReadonly"
              v-model="formData.grantReason"
              placeholder="请输入放发原因"
              clearable
            />
            <span v-else>{{ formData.grantReason }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="领用部门" prop="receiveDepartmentName">
            <el-input
              disabled
              v-if="!props.isReadonly"
              v-model="formData.receiveDepartmentName"
              placeholder="请输入领用部门"
              clearable
            />

            <span v-else>{{ formData.receiveDepartmentName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="领用人" prop="receivePersonName">
            <el-input
              disabled
              v-if="!props.isReadonly"
              v-model="formData.receivePersonName"
              placeholder="请输入领用人"
              clearable
            />

            <span v-else>{{ formData.receivePersonName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="归还日期" prop="repayDate">
            <el-date-picker
              style="width: 300px"
              v-if="!props.isReadonly"
              v-model="formData.repayDate"
              type="date"
              placeholder="请选择归还日期"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
            />
            <span v-else>
              {{
                formData.repayDate
                  ? dayjs(formData.repayDate).format("YYYY-MM-DD")
                  : ""
              }}
            </span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归还原因" prop="returnReason">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.returnReason"
              placeholder="请输入归还原因"
              clearable
            />

            <span v-else>{{ formData.returnReason }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="归还人" prop="repayPersonName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.repayPersonName"
              placeholder="请输入归还人"
              clearable
            />

            <span v-else>{{ formData.repayPersonName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="归还位置" prop="locationAfterRepayId">
            <el-tree-select
              placeholder="请输入归还位置"
              style="width: 300px"
              filterable
              v-if="!props.isReadonly"
              v-model="formData.locationAfterRepayId"
              :data="locationInfoTree"
              node-key="id"
              clearable
              :props="{ label: 'locationName', children: 'nodes' }"
              check-strictly
              @node-click="changeLocation"
              :render-after-expand="false"
            />
            <span v-else>{{ formData.locationAfterRepay }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import dayjs from "dayjs";

defineOptions({
  name: "REPAYMANAGEEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  assetId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  isRepay: [],
  returnReason: [
    { required: true, message: "请输入归还原因", trigger: "blur" },
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  repayDate: [{ required: true, message: "请选择归还日期", trigger: "change" }],
  repayPersonId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  repayPersonName: [
    { required: true, message: "请输入归还人", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  locationAfterRepayId: [
    { required: true, message: "请选择归还位置", trigger: "change" },
  ],
  locationAfterRepay: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  recordId: "",
  seq: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  usingDepartmentId: "",
  usingDepartmentName: "",
  usingPersonId: "",
  usingPersonName: "",
  locationBeforeGrantId: "",
  locationBeforeGrant: "",
  locationAfterGrantId: "",
  locationAfterGrant: "",
  isRepay: "",
  returnReason: "",
  repayDate: "",
  repayPersonId: "",
  repayPersonName: "",
  locationAfterRepayId: "",
  locationAfterRepay: "",
  remarks: "",
  deleted: "",
  organizationId: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  grantDate: "",
  grantReason: "",
  receiveDepartmentName: "",
  receivePersonName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        recordId,
        seq,
        assetId,
        assetCode,
        assetName,
        usingDepartmentId,
        usingDepartmentName,
        usingPersonId,
        usingPersonName,
        locationBeforeGrantId,
        locationBeforeGrant,
        locationAfterGrantId,
        locationAfterGrant,
        isRepay,
        returnReason,
        repayDate,
        repayPersonId,
        repayPersonName,
        locationAfterRepayId,
        locationAfterRepay,
        remarks,
        deleted,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        grantDate,
        grantReason,
        receiveDepartmentName,
        receivePersonName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        recordId,
        seq,
        assetId,
        assetCode,
        assetName,
        usingDepartmentId,
        usingDepartmentName,
        usingPersonId,
        usingPersonName,
        locationBeforeGrantId,
        locationBeforeGrant,
        locationAfterGrantId,
        locationAfterGrant,
        isRepay,
        returnReason,
        repayDate,
        repayPersonId,
        repayPersonName,
        locationAfterRepayId,
        locationAfterRepay,
        remarks,
        deleted,
        organizationId,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        grantDate,
        grantReason,
        receiveDepartmentName,
        receivePersonName,
      });

      formData.locationAfterRepayId = locationBeforeGrantId;
      formData.locationAfterRepay = locationBeforeGrant;
      // 格式
      if (props.isReadonly == true) {
        formData.repayDate = formData.repayDate;
      } else {
        // 当前值
        formData.repayDate = formData.repayDate
          ? formData.repayDate
          : dayjs(new Date()).format("YYYY-MM-DD");
      }
      formData.grantDate = formData.grantDate
        ? dayjs(formData.grantDate).format("YYYY-MM-DD")
        : "";
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.recordId = "";
  formData.seq = "";
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
  formData.usingDepartmentId = "";
  formData.usingDepartmentName = "";
  formData.usingPersonId = "";
  formData.usingPersonName = "";
  formData.locationBeforeGrantId = "";
  formData.locationBeforeGrant = "";
  formData.locationAfterGrantId = "";
  formData.locationAfterGrant = "";
  formData.isRepay = "";
  formData.returnReason = "";
  formData.repayDate = "";
  formData.repayPersonId = "";
  formData.repayPersonName = "";
  formData.locationAfterRepayId = "";
  formData.locationAfterRepay = "";
  formData.remarks = "";
  formData.deleted = "";
  formData.organizationId = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.grantDate = "";
  formData.grantReason = "";
  formData.receiveDepartmentName = "";
  formData.receivePersonName = "";
}

const loading = ref(false);

/** 发放记录明细保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      if (formData.repayDate < formData.grantDate) {
        ElMessage.error("归还日期不能小于发放日期");
        return;
      }

      loading.value = true;
      const text = formData.id ? "归还" : "新增";
      await request({
        url: "/eam/mtgrantrecord/saveReturnRecords",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

// 点击位置树
const changeLocation = (e) => {
  if (e) {
    formData.locationAfterRepayId = e.id;
    formData.locationAfterRepay = e.locationName;
  } else {
    formData.locationAfterRepayId = "";
    formData.locationAfterRepay = "";
  }
};

onMounted(() => {
  getLocationInfoTree();
}),
  // 组件销毁时调用
  onBeforeUnmount(() => {
    visibleDialog.value = false;
    emit("change-visible", false);
  });
</script>
